from flask import g, Blueprint, request
from app.api import handle_error, verify_params
from app.util.jwt import auth_check
from app.common.result import trueReturn, falseReturn
from app.models.Sentence import Sentence

sentence_blueprint = Blueprint('sentence_blueprint', __name__, url_prefix='/sentence')


@sentence_blueprint.before_request
@handle_error
def before_request():
    if (request.method == 'POST' or request.method == 'PUT') and request.get_data():
        g.data = request.get_json()
    elif request.method == 'GET' or request.method == 'DELETE':
        g.data = request.args
    else:
        g.data = {}
    Authorization = request.headers.get('Authorization', None)
    auth_check(Authorization)


@sentence_blueprint.route('', methods=['GET'])
@handle_error
@verify_params(params=['by'])
def get_sentence():
    if g.auth_id is None:
        return falseReturn(msg='您尚未登录，权限不足')
    by = g.data.get('by', None)
    if by == 'all':
        student_list = Sentence.get_talk_list()
        return trueReturn(data={"studentList": student_list}, msg='查询成功')
    elif by == 'single':
        auth_id = g.data.get('auth_id', None)
        if auth_id is None:
            return falseReturn(msg='未找到auth_id，请检查')
        sentence_list = Sentence.get_sentence_by_username(auth_id=auth_id)
        return trueReturn(data={"sentenceList": sentence_list}, msg='查询成功')
    else:
        return falseReturn(msg='请求类型错误，请检查')
